package com.automation.monkeytalk;

import java.io.File;

import org.junit.Test;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;


public class RunExcelMacro {
    
  
final File file = new File( "C:\\Users\\Divya\\Desktop\\demo.xlsm");
final String macroName = "!Module1.demo";
    
@Test
public void runMacro() {
    callExcelMacro(file, macroName);
}


public  void callExcelMacro(File file, String macroName) {
    ComThread.InitSTA();

    final ActiveXComponent excel = new ActiveXComponent("Excel.Application");

    try {
           //This will open the excel if the property is set to true    
          // excel.setProperty("Visible", new Variant(true));

     final Dispatch workbooks = excel.getProperty("Workbooks") .toDispatch();
     final Dispatch workBook = Dispatch.call(workbooks, "Open", file.getAbsolutePath()).toDispatch(); 
                                                   

     // Calls the macro
      final Variant result = Dispatch.call(excel, "Run", new Variant(file.getName()+ macroName));

        // Saves and closes
        Dispatch.call(workBook, "Save");
                            
        com.jacob.com.Variant f = new com.jacob.com.Variant(true);
        Dispatch.call(workBook, "Close", f);

        } catch (Exception e) {
                  e.printStackTrace();
        } finally {

                excel.invoke("Quit", new Variant[0]);
                ComThread.Release();
        }

}
	
	
}